package org.toools.gwt.wmc.server.additive;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.Collection;
import org.toools.gwt.wmc.client.additive.AdditiveService;
import org.toools.gwt.wmc.server.dao.IAdditiveDAO;
import org.toools.gwt.wmc.jpa.Additive;
import org.toools.gwt.wmc.server.WMCSession;

public class AdditiveServiceImpl extends RemoteServiceServlet implements AdditiveService {

    private IAdditiveDAO additivedao;

    /** Account DAO **/
    public void setAdditivedao( IAdditiveDAO dao ) {
        this.additivedao = dao;
    }
    public IAdditiveDAO getAdditivedao() {
		return additivedao;
	}

    public Additive getAdditiveByID(Integer ID) {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) || additivedao.belongsTo( ID, WMCSession.getAccountID( getThreadLocalRequest() ) ) )
            return additivedao.getAdditiveByID( ID );

        return null;
    }

    public Collection<Additive> getAdditives() {
        if( ! WMCSession.isAdmin( getThreadLocalRequest() ) )
            return additivedao.getAdditives( WMCSession.getAccountID( getThreadLocalRequest() ) );
        return additivedao.getAdditives();
    }

    public Additive create(Additive a) {
        //check if additive belongs to account ?!?
        return additivedao.create( a );
    }

    public Boolean update(Additive a) {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) || additivedao.belongsTo( a.getId(), WMCSession.getAccountID( getThreadLocalRequest() ) ) )
            return additivedao.update( a );
        return false;
    }

    public Boolean delete(Additive a) {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) || additivedao.belongsTo( a.getId(), WMCSession.getAccountID( getThreadLocalRequest() ) ) )
            return additivedao.delete( a );
        return false;
    }
}